package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"zhihu/mobels/cache"
	"zhihu/mobels/mysql"
	"zhihu/pkg"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *zhihurpc.UpdatePasswordRequest) (*zhihurpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"updatePassword"+in.Mobile)
	if get.Val() != in.CodeSms {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	var user mysql.User
	mysql.DB.Where("mobile = ? ", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号存在，请先注册")
	}

	if in.Password != in.PasswordNew {
		return nil, fmt.Errorf("两次密码输入不一致")
	}

	user = mysql.User{
		Model: gorm.Model{
			ID: user.ID,
		},
		Password: pkg.Md5(in.PasswordNew),
	}
	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}

	//修改成功后删除短信验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"updatePassword"+in.Mobile)
	return &zhihurpc.UpdatePasswordResponse{UserId: int64(user.ID)}, nil
}
